# -*- coding: utf-8 -*-
# windows 下如果出现编码问题，将 utf-8 改为 cp936
# 统计成绩
import re

# 打开并读取文件内容
with open('score.txt') as file_score:
    lines = file_score.readlines()

result = {}
for line in lines:
    # 提取非数字非空格部分
    re_name = re.compile(r'[^\d ]+')
    search_name = re_name.search(line)
    if search_name:
        name = search_name.group(0)
    # 提取数字部分
    re_score = re.compile(r'\d+')
    search_score = re_score.search(line)
    if search_score:
        score = search_score.group(0)
    # 累计分数和次数
    old_result = result.get(name, (0, 0))
    result[name] = (old_result[0] + int(score), old_result[1] + 1)

# 对结果进行排序
sorted_result = sorted(result.items(), key=lambda x: x[1][0], reverse=True)

data = []
for r in sorted_result:
    # 将每一人的成绩格式化，同时计算平均分
    s = '%s\t%d\t%d\t%.1f\n' % (r[0], r[1][0], r[1][1], float(r[1][0]) / r[1][1])
    data.append(s)

# 保存文件
with open('result.txt', 'w') as file_result:
    file_result.writelines(data)
